<template>
  <div class="flowchart-container">
    <div class="node" v-for="(node, index) in nodes" :key="node.id" :id="'node-' + node.id" :style="getNodeStyle(node)">
      <div class="node-content">{{ node.name }}</div>
    </div>
  </div>
</template>

<script>
import { jsPlumb } from 'jsplumb'

export default {
  data() {
    return {
      nodes: [
        { id: 1, name: 'Start', x: 100, y: 100 },
        { id: 2, name: 'Process A', x: 300, y: 100 },
        { id: 3, name: 'Process B', x: 500, y: 100 },
        { id: 4, name: 'End', x: 700, y: 100 },
        { id: 5, name: '最后', x: 700, y: 200 },
      ],
      connections: [
        { source: 1, target: 2 },
        { source: 2, target: 3 },
        { source: 3, target: 4 },
        { source: 4, target: 5 },
      ],
    };
  },
  mounted() {
    this.initializeJsPlumb();
  },
  methods: {
    initializeJsPlumb() {
      const instance = jsPlumb.getInstance({
        Connector: ['Straight'],
        PaintStyle: {stroke: '#000', strokeWidth: 2},
        // Endpoint: ['Dot', {radius: 5}],
        // EndpointStyle: {fill: '#000'},
        Endpoint: ['Blank',{}], // 设置为空白端点
        Anchor: 'Continuous',
        Overlays: [
          // 添加箭头
          ['Arrow', { location: 1, width: 10, length: 20, foldback: 0.8 }]
        ],
      });

      this.connections.forEach(connection => {
        instance.connect({
          source: `node-${connection.source}`,
          target: `node-${connection.target}`,
        });
      });

      // this.nodes.forEach(node => {
      //   instance.draggable(`node-${node.id}`);
      // });
    },
    getNodeStyle(node) {
      return {
        position: 'absolute',
        left: `${node.x}px`,
        top: `${node.y}px`,
        width: '100px',
        height: '50px',
        backgroundColor: '#4CAF50',
        color: 'white',
        textAlign: 'center',
        lineHeight: '50px',
        borderRadius: '5px',
        cursor: 'move',
      };
    },
  },
};
</script>

<style scoped>
.flowchart {
  position: relative;
  height: 200px;
}

.flowchart-container {
  position: relative;
  width: 100%;
  height: 400px;
  border: 1px solid #ccc;
  overflow: hidden; /* 防止溢出 */
}
.node {
  position: absolute;
  cursor: move;
}

.node-content {
  font-size: 14px;
}
</style>
